package com.doit.hbase.client2;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.BufferedMutator;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

/**
 * @DATE 2021/12/15/9:25
 * @Author MDK
 * @Version 2021.2.2
 *  添加数据
 *      原来的put请求需要多次连接服务器,给服务器增加压力,现采用批量导入的方法
 *      1.BufferedMutator 数据经过一定时间  一定的大小 写一次
 *      2.Bytes.toXX  将各种数据类型转换成字节数组  将字节数组转换成各种数据类型
 *      3.Put是  Mutation的子类 继承自mutate
 **/
public class C01_Mutation {
    public static void main(String[] args) throws Exception {
        Configuration configuration = HBaseConfiguration.create();
        configuration.set("hbase.zookeeper.quorum","linux01:2181,linux02:2181,linux03:2181");
        Connection connection = ConnectionFactory.createConnection(configuration);

        //获取执行批量导入的对象
        BufferedMutator bufferedMutator = connection.getBufferedMutator(TableName.valueOf("tb_teacher"));
        Put put = new Put(Bytes.toBytes("rk003"));
        put.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("name"),Bytes.toBytes("lisi"));
        put.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("age"),Bytes.toBytes(34));
        put.addColumn(Bytes.toBytes("cf"),Bytes.toBytes("gender"),Bytes.toBytes("M"));

        //put继承自mutate,因此可直接传值
        bufferedMutator.mutate(put);
        bufferedMutator.flush();  //刷新可在列表中添加值
        //也可设置刷写时间间隔
        bufferedMutator.setWriteBufferPeriodicFlush(1000*60*10);   //每隔10min刷写一次

        connection.close();
    }
}
